package com.vito.demo.hibernate.demo1

import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.Transaction
import org.hibernate.boot.registry.StandardServiceRegistryBuilder
import org.hibernate.cfg.Configuration
import org.hibernate.service.ServiceRegistry
import java.util.*

/**
 * Created by lingzhiyuan.
 * Date : 16/3/31.
 * Time : 下午6:08.
 * Description:
 *
 * 所有配置项前面必须加hibernate
 *
 */

fun main(args: Array<String>) {

    var properties: Properties = Properties();
    properties.setProperty("hibernate.connection.driver_class", "com.mysql" +
                                                                ".jdbc.Driver")
    properties.setProperty("hibernate.connection.url",
                           "jdbc:mysql://localhost/test?characterEncoding=utf8")
    properties.setProperty("hibernate.connection.username", "test")
    properties.setProperty("hibernate.connection.password", "test")

    properties.setProperty("hibernate.show_sql", "true")
    properties.setProperty("hibernate.format_sql", "false")
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect" + ".MySQL5InnoDBDialect")

    //连接池配置，生产环境必须用c3p0

    //初始化时获取三个连接，取值应在minPoolSize与maxPoolSize之间。Default: 3
    properties.setProperty("hibernate.c3p0.min_size", "1")
    //连接池中保留的最大连接数。Default: 15
    properties.setProperty("hibernate.c3p0.max_size", "20") //最大连接数
    //当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 5
    properties.setProperty("hibernate.c3p0.acquire_increment", "2")
    //每60秒检查所有连接池中的空闲连接。Default: 0
    properties.setProperty("hibernate.c3p0.idle_test_period", "200")

    //JDBC的标准参数，用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
    //属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
    //如果maxStatements与maxStatementsPerConnection均为0，则缓存被关闭。Default: 0
    properties.setProperty("hibernate.c3p0.max_statements", "100")

    //最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
    properties.setProperty("hibernate.c3p0.timeout", "1000")
    properties.setProperty("hibernate.c3p0.validate", "true")

    properties.setProperty("hibernate.hbm2ddl.auto", "update")


    var config: Configuration = Configuration()
            .addAnnotatedClass(NewsEntity::class.java)
            .setProperties(properties)

    var serviceRegistry: ServiceRegistry = StandardServiceRegistryBuilder()
            .applySettings(config.properties)
            .build()

    var sessionFactory: SessionFactory = config.buildSessionFactory(serviceRegistry)
    var session: Session = sessionFactory.openSession()
    var transaction: Transaction = session.beginTransaction()

    var news: NewsEntity = NewsEntity()
    news.title = "hello"
    news.content = "from kotlin"

    session.save(news)
    transaction.commit()
    session.close()
    sessionFactory.close()

    print("\n over \n")

}